//  第一个载入的是如下格式，之后的直接用 appServe.factory()......
appServe
  .factory('UtilsService', function($cookieStore, $ionicHistory, $window, $rootScope, $state, UserService) {
    var utils = {};
    // 判断是否已经登录
    utils.isLogin = function() {
      return $window.localStorage['user'] != undefined;
    }

    utils.getUser = function() {
      return angular.fromJson($window.localStorage['user']);
    }

    utils.setUser = function(user) {
      if (user != null || user != undefined) {
        $window.localStorage['user'] = angular.toJson(user);
      } else {
        $window.localStorage.removeItem('user');
        // $cookieStore.remove('user');
      }
    }

    utils.isTokenExist = function() {
      return $window.localStorage['token'] != undefined;
    }

    utils.getToken = function() {
      return angular.fromJson($window.localStorage['token']);
    }

    utils.setToken = function(token) {
      if (token != null) {
        $window.localStorage['token'] = angular.toJson(token);
      } else {
        $window.localStorage.removeItem('token');
      }
    }

    utils.isDistExist = function() {
      return $window.localStorage['dist'] != undefined;
    }

    utils.getDist = function() {
      // console.log($window.localStorage['dist']);
      return angular.fromJson($window.localStorage['dist']);
    }

    utils.setDist = function(dist) {
      if (dist != null) {
        $window.localStorage['dist'] = angular.toJson(dist);
        // $cookieStore.put('dist', dist);
      } else {
        $window.localStorage.removeItem('dist');
      }
    }


    utils.clearCookie = function() {
      $window.localStorage.removeItem('token');
      $window.localStorage.removeItem('dist');
      $window.localStorage.removeItem('user');
    }

    utils.getAid = function() {
      if ($window.localStorage['dist']) {
        return angular.fromJson($window.localStorage['dist'])['a_repository_id'];
      }
      return undefined;
    }

    utils.isResponseOk = function(response) {
      return response.state.code == 200;
    }

    utils.goBack = function() {
      $ionicHistory.goBack();
    }


    utils.logout = function() {
      UserService.logout().$promise.then(function(response) {
        if (utils.isResponseOk(response)) {
          utils.clearCookie();
          $state.transitionTo('district.list', {}, {
            reload: true
          });
          $rootScope.$broadcast('loading:showMessage', {
            message: '注销成功，请重新选择地址'
          })
        }
      })
    }

    return utils;
  });
